<template>
    <view class="home-content">
        <!-- 分类 -->
        <view class="content-category">
            <view class="content-list">
                <view
                    class="list-item"
                    :class="{ active: activeId === -1 }"
                    @click="handleTabClick(-1)"
                    >推荐</view
                >
                <view
                    v-for="(item, index) in categoryArr"
                    :key="item.id"
                    class="list-item"
                    :class="{ active: item.id === activeId }"
                    @click="handleTabClick(item.id)"
                >
                    {{ item.name }}
                </view>
            </view>
            <han-icon name="open" size="38" class="icon" />
        </view>

        <!-- 帖子内容 -->
        <view class="post-content">
            <!-- 下拉刷新提示 -->
            <view v-if="isRefreshing" class="refresh-indicator">
                <text>刷新中...</text>
            </view>

            <!-- 空状态提示 -->
            <view v-if="!isLoading && posts.length === 0" class="empty-state">
                <text class="empty-text">该分类下暂无帖子</text>
            </view>

            <postList :content="posts" :isLoading="isLoading" />

            <!-- 没有更多数据提示 -->
            <view v-if="!hasMore && posts.length > 0" class="no-more">
                <text>没有更多帖子了</text>
            </view>
        </view>
    </view>
</template>

<script setup>
import postList from '../../post/subpages/post_list/postList.vue';
import { ref, onMounted } from 'vue';
import { CATEGORY_BY_ID } from '@/util/config/post.config.js';
import { getAllPosts, getPostsByCategoryId } from '@/apis/postAPI';

// 将分类对象转为数组 [{id, name}]
const categoryArr = ref(
    Object.entries(CATEGORY_BY_ID).map(([id, name]) => ({
        id: Number(id),
        name
    }))
);

const activeId = ref(-1); // -1为推荐
const posts = ref([]);
const isLoading = ref(false);
const isRefreshing = ref(false);
const hasMore = ref(true);

const pagination = ref({
    current: 1,
    size: 20,
    pages: 1
});

const fetchPosts = async (isRefresh = false) => {
    try {
        if (isRefresh) {
            isRefreshing.value = true;
            pagination.value.current = 1;
        } else {
            if (pagination.value.current >= pagination.value.pages) {
                hasMore.value = false;
                return;
            }
            isLoading.value = true;
            pagination.value.current += 1;
        }

        let res;
        if (activeId.value === -1) {
            res = await getAllPosts(
                pagination.value.current,
                pagination.value.size
            );
        } else {
            res = await getPostsByCategoryId(
                activeId.value,
                pagination.value.current,
                pagination.value.size
            );
        }

        pagination.value = {
            ...pagination.value,
            size: res.data.data.size,
            pages: res.data.data.pages,
            total: res.data.data.total
        };

        if (isRefresh) {
            posts.value = res.data.data.records;
        } else {
            posts.value = [...posts.value, ...res.data.data.records];
        }

        hasMore.value = pagination.value.current < pagination.value.pages;
    } catch (error) {
        console.error('获取帖子失败:', error);
        if (!isRefresh) {
            pagination.value.current -= 1;
        }
        uni.showToast({
            title: '加载失败，请重试',
            icon: 'none'
        });
    } finally {
        isLoading.value = false;
        isRefreshing.value = false;
    }
};

const onRefresh = () => {
    if (!isRefreshing.value) {
        fetchPosts(true);
    }
};

const onLoadMore = () => {
    if (!isLoading.value && hasMore.value) {
        fetchPosts();
    }
};

onMounted(() => {
    fetchPosts(true);
});

const handleTabClick = (id) => {
    activeId.value = id;
    pagination.value = {
        current: 1,
        size: 10,
        pages: 1
    };
    hasMore.value = true;
    fetchPosts(true);
};

defineExpose({
    onRefresh,
    onLoadMore
});
</script>

<style lang="scss">
.home-content {
    .empty-state,
    .refresh-indicator {
        text-align: center;
        padding-bottom: 100rpx;
    }

    .content-category {
        display: flex;
        align-items: center; // 垂直居中
        width: 100%;

        .content-list {
            display: flex;
            width: 90%; // 占满父容器宽度
            overflow-x: auto; // 水平滚动
            white-space: nowrap; // 防止文字换行
            -webkit-overflow-scrolling: touch; // iOS平滑滚动
            scroll-behavior: smooth; // 启用平滑滚动
            transition: all 0.3s ease; // 添加过渡效果

            .list-item {
                padding: 5rpx 10rpx; // 内外边距
                white-space: nowrap; // 内容不换行
            }

            .active {
                color: $han-global-primary-font-color;
                font-weight: bold;
            }
        }

        .icon {
            margin-left: auto;
            margin-right: 20rpx;
        }
    }

    .post-content {
        position: relative;
        padding-bottom: 30rpx;
        margin: 20rpx;

        .no-more {
            position: absolute;
            bottom: 20rpx;
            left: 0;
            width: 100%;
            text-align: center;
            padding: 20rpx 0;
            color: $han-global-primary-font-color;
            font-size: 24rpx;
        }
    }
}
</style>
